	//
//  CXHomeController.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/18.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit
import SVProgressHUD

class CXHomeController: CXVisiterController {
    /// 保存原微博个数
    var prevStatusCount:Int = 0
    
    /// 控制器直接拥有viewModel 而不再是 Model
    lazy var statuslist:CXStatusListViewModel = {
        return CXStatusListViewModel()
    }()
    /// 上拉控件
    private lazy var pullup: UIActivityIndicatorView = {
        let pl = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
        pl.backgroundColor = UIColor.yellowColor()
        return pl
    }()
    /// 下拉控件
    private lazy var pulldown: CXRefreshControl = {
        let pd = CXRefreshControl()
        //将加载数据的监听加入下拉控件
        pd.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        return pd
    }()
    /// 模拟官方版 下拉刷新后弹出刷新信息视图的效果. UILabel也可以含有背景颜色哦。。
    private lazy var pulldownAttach: UILabel = {
        let pdattch = UILabel(textColor: UIColor.blackColor(), font: 14)
        pdattch.backgroundColor = UIColor.orangeColor()
        pdattch.textAlignment = .Center
        pdattch.frame.size = CGSize(width: SCREENW, height: 35)
        pdattch.hidden = true
        return pdattch
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册 还有行高
        tableView.registerClass(CXHomeStatusCell.self, forCellReuseIdentifier: CXHomeCellID)
        
        setupUI()
        if visiterView != nil {
            visiterView?.setupInfo(nil, message: "关注一些人，回这里看看有什么惊喜关注一些人，回这里看看有什么惊喜")
        }
        //设置预估行高 提升性能
        tableView.estimatedRowHeight = 200
        tableView.showsVerticalScrollIndicator = false
        tableView.rowHeight = UITableViewAutomaticDimension //自动设置行高 自动布局
        tableView.separatorStyle = .None  //取消分割线
        //TODO:设置上拉加载和下拉刷新的控件
        tableView.tableFooterView = pullup
        tableView.addSubview(pulldown)
        
        loadData()
    }
    func setupUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageNamed: "navigationbar_friendsearch", target: nil, action: "")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageNamed: "navigationbar_pop", target: self, action: "push")
        
        //将这个显示刷新信息的视图添加在导航条与当前控制器的view之间
        if let naviBar = navigationController?.navigationBar {
            navigationController!.view.insertSubview(pulldownAttach, belowSubview: naviBar)
        }
    }
    //载入数据
    @objc private func loadData() {
        //TODO: 修改为带有上拉和下拉操作的参数的方法
        statuslist.loadStatuses(isPullup: pullup.isAnimating()) { (isSuccess, count) -> Void in
            if isSuccess {
                //是下拉
                if !self.pullup.isAnimating() {
//                    self.pulldown.deltaInfo = self.statuslist.statusArray!.count - self.prevStatusCount
//                    self.prevStatusCount = self.statuslist.statusArray!.count
                    
                    self.setupPulldownAnim(newadded: count)
                }
                self.tableView.reloadData()
            } else {
                SVProgressHUD.showErrorWithStatus("首页获取微博数据失败!")
            }
            //加载完毕数据后 让上拉的动画停止
            //并调用系统方法停止刷新
            self.pullup.stopAnimating()
            //系统方法
            self.refreshControl?.endRefreshing()
            self.pulldown.endAnimation()
            
        }
    }
    @objc private func push() {
        print("push了")
        let vc = CXTempController()
        navigationController?.pushViewController(vc, animated: true)
    }
    ///  设置并展示下拉刷新附加动画
    private func setupPulldownAnim(newadded newadded: Int) {
        
        let navibar = navigationController!.navigationBar
        pulldownAttach.frame.origin.y = CGRectGetMaxY(navibar.frame) - pulldownAttach.frame.height
        
        //如果已经不隐藏 说明正在动画中
        if pulldownAttach.hidden == false {
            return
        }
        pulldownAttach.hidden = false
        pulldownAttach.text = (newadded == 0) ? "没有新微博" : "新增了\(newadded)条微博"
        //开始动画
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.pulldownAttach.transform = CGAffineTransformTranslate(self.pulldownAttach.transform, 0, self.pulldownAttach.frame.height)
            
            }) { (_) -> Void in
                
                UIView.animateWithDuration(1, delay: 0.5, options: [], animations: { () -> Void in
                    self.pulldownAttach.transform = CGAffineTransformIdentity
                    
                    }, completion: { (_) -> Void in
                        self.pulldownAttach.hidden = true
                })
        }
    }
}
extension CXHomeController {
    
    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

//        if let count = statuslist.statusArray?.count where count != 0 {
//            prevStatusCount = count
//        }
        return statuslist.statusArray?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(CXHomeCellID, forIndexPath: indexPath) as! CXHomeStatusCell
        //TODO: 给Cell赋模型？ 还是视图模型？
        cell.statusViewModel = statuslist.statusArray![indexPath.row]
        cell.selectionStyle = .None  //取消输出样式
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statuslist.statusArray!.count - 1 && !pullup.isAnimating() {
            //即将滚动到最后一个 且上拉控件还没动画
            loadData()
            pullup.startAnimating()
        }
    }
}
